package ximage

import (
	"image"
	"image/draw"
	"os"
	"path/filepath"
)

type Position uint32

const (
	LeftTop Position = iota
	LeftBottom
	RightTop
	RightBottom
	Center
)

//WaterMark打水印相关信息封装
type WaterMark struct {
	//原始图片文件名
	SrcImageFileName string
	//生成水印图片文件名
	DestImageFileName string
	//水印图片文件名
	WaterMarkFileName string
	//水印在原始图片上的位置，有LeftTop(左上角),LeftBottom(左下角),RightTop(右上角),RightBottom(右下角),Center(居中)；
	//如果WaterMarkPosition为nil是默认为RightBottom
	WaterMarkPosition Position
}

//DrawWaterMark打水印
func (this *WaterMark) DrawWaterMark() error {
	srcFile, err := os.Open(this.SrcImageFileName)
	if err != nil {
		return err
	}
	defer srcFile.Close()
	src, _, err := image.Decode(srcFile)
	if err != nil {
		return err
	}

	waterMarkFile, err := os.Open(this.WaterMarkFileName)
	if err != nil {
		return err
	}
	defer waterMarkFile.Close()
	watermark, _, err := image.Decode(waterMarkFile)
	if err != nil {
		return err
	}

	destImageFile, err := os.Create(this.DestImageFileName)
	if err != nil {
		return err
	}
	defer destImageFile.Close()

	var computeWaterMarkOffset = func(p Position) image.Point {
		var offset image.Point
		var padding = 10
		switch p {
		case LeftTop:
			offset = image.Pt(padding, padding)
		case LeftBottom:
			offset = image.Pt(padding, src.Bounds().Dy()-watermark.Bounds().Dy()-padding)
		case RightTop:
			offset = image.Pt(src.Bounds().Dx()-watermark.Bounds().Dx()-padding, padding)
		case Center:
			offset = image.Pt(src.Bounds().Dx()/2-watermark.Bounds().Dx()/2, src.Bounds().Dy()/2-watermark.Bounds().Dy()/2)
		default:
			offset = image.Pt(src.Bounds().Dx()-watermark.Bounds().Dx()-padding, src.Bounds().Dy()-watermark.Bounds().Dy()-padding)
		}
		return offset
	}

	lastIamge := image.NewNRGBA(src.Bounds())
	draw.Draw(lastIamge, src.Bounds(), src, image.ZP, draw.Src)
	draw.Draw(lastIamge, watermark.Bounds().Add(computeWaterMarkOffset(this.WaterMarkPosition)), watermark, image.ZP, draw.Over)

	ext := filepath.Ext(this.DestImageFileName)
	if dofunc, ok := writeImageFunMap[ext]; ok {
		return dofunc(destImageFile, lastIamge)
	} else {
		return fileExtNotSupport
	}
}
